import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Table, MessagePlugin, Tag, Popconfirm } from 'tdesign-react'
import { EditIcon, MenuUnfoldIcon, DeleteIcon } from 'tdesign-icons-react'
import { useTranslation } from 'react-i18next'
import moment from 'moment'
import { ApiRequest, apis } from '@/service'
import TableOperateButton from '@/components/Table/TableOperateButton'
import type { BaseTableCol } from 'tdesign-react'

const {
  getBugList,
  deleteBugItem,
} = apis.BMService.test


const ShowBugs = () => {

  const { t } = useTranslation(["bugManager"])
  const navigate = useNavigate()
  const [tableData, setTableData] = useState<any[]>([])
  const [total, setTotal] = useState<number>(0)
  const currentDate = moment().format('YYYY-MM-DD')

  const columns: BaseTableCol[] = [
    {
      colKey: 'priority',
      title: t(`test.priority`),
      minWidth: 60,
      cell: ({ row }: { row: any }) => (
        row.priority.label
      ),
    },
    {
      colKey: 'title',
      title: t(`test.title`),
      minWidth: 240,
      ellipsis: true,
    },
    {
      colKey: 'processo',
      title: t(`test.owner`),
      minWidth: 80,
      cell: ({ row }: { row: any }) => (
        row.processor?.[0]?.label
      )
    },
    {
      colKey: 'isOverdue',
      title: t(`test.isOverdue`),
      minWidth: 80,
      align: 'center',
      cell: ({ row }: { row: any }) => (
        <Tag
          className='table-tag'
          shape='square'
          theme={row.deadline < currentDate ? 'danger' : 'success'}
          // variant="light-outline"
        >
          {row.deadline < currentDate ? '已超期' : '未超期'}
        </Tag>
      ),
    },
    {
      colKey: 'creator',
      title: t(`test.creator`),
      minWidth: 80,
    },
    {
      colKey: 'createTime',
      title: t(`test.createTime`),
      minWidth: 100,
      ellipsis: true,
    },
    {
      colKey: 'steps',
      title: t(`test.steps`),
      minWidth: 60,
      cell: ({ row }: { row: any }) => (
        row.steps?.[0]?.label
      ),
    },
    {
      colKey: 'operate',
      title: t(`test.operate`),
      align: 'center',
      fixed: 'right',
      thClassName: 'table-fixed-th',
      cell: ({ row }: { row: any }) => (
        <div className='tdesign-table-demo__table-operations'>
          <TableOperateButton Icon={<EditIcon />} onClick={() => { toEditBugItem(row) }} />
          <TableOperateButton Icon={<MenuUnfoldIcon />} onClick={() => { toShowBugDetail(row) }} />
          <Popconfirm
            content="确认删除吗"
            destroyOnClose
            placement="top"
            showArrow
            theme="default"
            onConfirm={() => { toDeleteBugItem(row) }}
          >
            <>
              <TableOperateButton Icon={<DeleteIcon />} />
            </>
          </Popconfirm>
        </div>
      )
    }
  ]

  useEffect(() => {
    queryTableData()
  }, [])

  const queryTableData = () => {
    const params = {}
    ApiRequest({ api: getBugList, params }).then((res: ResponseDataType) => {
      const { code = -1, data = [], note = '', total = 0 } = res
      if (code > 0) {
        setTableData(data)
        setTotal(total)
      } else {
        MessagePlugin.error({
          content: note,
          placement: 'top-right',
          duration: 2000
        })
      }
    })
  }

  const toEditBugItem = (item: any) => {
    navigate('/aio/bug-manager/test/create-bug', {
      state: {
        id: item.id
      }
    })
  }

  const toShowBugDetail = (item: any) => {
    navigate('/aio/bug-manager/test/bug-detail', {
      state: {
        id: item.id,
      }
    })
  }

  const toDeleteBugItem = (item: any) => {
    let params = {
      id: item.id
    }
    ApiRequest({ api: deleteBugItem, params: params }).then((res: ResponseDataType) => {
      const { code = -1, data = [], note = '' } = res
      if (code > 0) {
        MessagePlugin.success({
          content: note || '删除成功',
          placement: 'top-right',
          duration: 2000
        })
      } else {
        MessagePlugin.error({
          content: note || '删除失败',
          placement: 'top-right',
          duration: 2000
        })
      }
    })
    queryTableData()
  }

  return <div className={'content-wrapper'}>
    <Table
      className='bm-table'
      data={tableData}
      columns={columns}
      rowKey={'id'}
      verticalAlign={'top'}
      bordered={true}
      showHeader={true}
      tableLayout={'auto'}
      rowClassName={({ rowIndex }) => `${rowIndex}-class`}
      cellEmptyContent={'--'}
      resizable={false}
      size='small'
      loading={tableData.length ? false : true}
      pagination={{
        defaultCurrent: 1,
        defaultPageSize: 10,
        total,
        showJumper: true,
        size: 'small',
      }}
    />
  </div>

}

export default ShowBugs
